import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/UI/AudioPlayerPage.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/AudioPlayBarNet.dart';
import 'package:hitutor/Widget/AudioPlayerBarLocal.dart';
import 'package:hitutor/Widget/MyBgPage.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyInput.dart';

import '../../WebPage.dart';
import 'CommentTeacher.dart';
import 'RecordList.dart';
import 'ReviewLiveChat.dart';
import 'SubmitHomeWork.dart';
import 'WordsShowCard.dart';
import 'WordsTest.dart';

class ReviewClass extends StatefulWidget {
  dynamic classData;

  ReviewClass(this.classData);

  @override
  State<StatefulWidget> createState() {
    return _ReviewClass();
  }
}

class _ReviewClass extends State<ReviewClass> {
  dynamic data;

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getData();
    });
    super.initState();
  }

  getData() {
    // widget.classData["classroomId"] = 2215396; //todo delete
    HttpGo(context).get("/Material/GetReviewClassroomInfo/?classroomId=${widget.classData["classroomId"]}", {}, (data) {
      this.data = data;
      setState(() {});
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    String beginTime = getStrTime(getTimeByUtc(widget.classData["beginTime"]), DateUtil.YMDHM);
    String endTime = getStrTime(getTimeByUtc(widget.classData["endTime"]), DateUtil.HM);
    String className = "${widget.classData["lessonName"]}";
    if (className.length > 10) {
      className = className.substring(0, 10) + "...";
    }

    Function() refreshData = () {
      getData();
    };

    return MyBgPage(
        "",
        data != null
            ? SingleChildScrollView(
                child: Column(children: [
                Container(height: 24),
                Text("$beginTime - $endTime", style: TextStyle(fontSize: 14, color: MyColor.Green, fontWeight: FontWeight.bold)),
                Text(className, style: TextStyle(fontSize: 14, height: 2, color: Color(0xffff8484), fontWeight: FontWeight.bold)),
                Text("授課老師：${data["teacherName"]}", style: TextStyle(fontSize: 13, height: 2, color: MyColor.C58)),
                TodayClassWidget(data),
                Visibility(visible: data["vocabularies"].length > 0, child: WordWidget(data)),
                TeacherNote(data),
                MyNote(data),
                Visibility(
                    visible: data["homework"]["question"] != null,
                    child: Homework("${data["teacherName"]}", "${data["teacherId"]}", data["homework"], refreshData)),
              ]))
            : Container());
  }
}

///今日課程
class TodayClassWidget extends StatefulWidget {
  dynamic data;
  List<dynamic> classedUrls = [];

  TodayClassWidget(this.data) {
    classedUrls = data["classedUrl"];
  }

  @override
  State<StatefulWidget> createState() {
    return _TodayClassWidget();
  }
}

class _TodayClassWidget extends State<TodayClassWidget> {
  ///評價
  comment() {
    if (widget.data["isCommnet"]) return;
    showWidgetDialog(
        context,
        CommentTeacher(
            lessonId: widget.data["lessonId"],
            classroomId: widget.data["classroomId"],
            commentWords: Global.commentWords,
            commentCallback: () {
              widget.data["isCommnet"] = true;
              setState(() {});
            }));
  }

  List<dynamic> reviewFiles = [];

  ///复习教材文档
  seeReviewFiles() {
    if (reviewFiles.length < 1) {
      showToast("暫無復習教材文檔");
      return;
    }
    PageUtil().open(context, AudioPlayerPage(mode: AudioPlayerPage.fileMode, Files: reviewFiles));
  }

  geReviewFiles() {
    HttpGo(context).get("/HiNote/GetReviewMaterial/?classroomId=${widget.data["classroomId"]}", {}, (data) {
      reviewFiles = data["description"];
    }, (code, error) => showToast(error));
  }

  downloadReviewFiles() {
    if (reviewFiles.length < 1) {
      showToast("暫無復習教材文檔");
      return;
    }
    showScaffoldDialog(context, DownloadDialog(reviewFiles));
  }

  ///上课录影
  seeRecord() {
    if (widget.classedUrls.length < 1) {
      showToast("暫無上課錄影");
      return;
    }
    PageUtil().open(context, RecordList(widget.classedUrls));
    // PageUtil().open(context, VideoPlayerPage(classedUrls[0]["url"]));
  }

  downloadRecord() async {
    if (widget.classedUrls.length < 1) {
      showToast("暫無上課錄影");
      return;
    }
    showScaffoldDialog(context, DownloadDialog(widget.classedUrls));
  }

  ///LiveChat
  List<dynamic> chatList = [];

  getLiveChat() {
    HttpGo(context).post("/HiNote/GetLiveChatDetail/", {
      "classroomId": widget.data["classroomId"],
      "teacherId": widget.data["teacherId"],
      "timeZone": DateTime.now().timeZoneOffset.inMinutes,
    }, (data) {
      chatList = data["chatList"];
    }, (code, error) => showToast(error));
  }

  seeLiveChat() {
    showWidgetDialog(context, ReviewLiveChat(chatList));
  }

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      geReviewFiles();
      getLiveChat();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: Global.getWhiteBg_shadow(8, MyColor.DD),
        padding: EdgeInsets.all(12),
        margin: EdgeInsets.all(12),
        child: Column(children: [
          Row(mainAxisAlignment: MainAxisAlignment.center, children: [
            LocalImage("book.png", height: 24, width: 32),
            Text("今日課程", style: TextStyle(fontSize: 14, color: MyColor.Orange, fontWeight: FontWeight.bold))
          ]),
          Container(height: 0.5, color: MyColor.Orange, margin: EdgeInsets.only(top: 6, bottom: 16)),
          Row(crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [
            Button("${widget.data["plateformName"]}",
                height: 22, width: 22, bgColor: MyColor.C5, radius: 20, fontSize: 11, margin: EdgeInsets.only(right: 4)),
            Text("${widget.data["className"]}", textAlign: TextAlign.center, style: TextStyle(fontSize: 12, color: MyColor.C7D))
          ]),
          Container(height: 16),
          Visibility(
              visible: !widget.data["isCommnet"],
              child: Button("評價", bgColor: MyColor.Orange, radius: 4, width: double.infinity, height: 32, fontSize: 12, onTap: comment)),
          Item("pic.png", "複習教材文檔", onSeeTap: seeReviewFiles, onDownloadTap: downloadReviewFiles,hideDownload: !widget.data["isDownloadFile"]),
          Item("video-camera_w.png", "上課錄影", onSeeTap: seeRecord, onDownloadTap: downloadRecord,hideDownload:  !widget.data["isDownloadMultiMedia"]),
          Item("chat_w.png", "Live Chat", onSeeTap: seeLiveChat, hideDownload: true),
        ]));
  }
}

class Item extends StatelessWidget {
  String icon;
  String title;
  bool hideSee = false;
  bool hideDownload = false;
  Function()? onSeeTap;
  Function()? onDownloadTap;

  Item(this.icon, this.title, {hideSee, hideDownload, this.onDownloadTap, this.onSeeTap}) {
    this.hideDownload = hideDownload ?? false;
    this.hideSee = hideSee ?? false;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: Global.getBg(Color(0xffecf9f9), 8),
        margin: EdgeInsets.only(top: 8),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Container(
              padding: EdgeInsets.all(8),
              child: Row(mainAxisSize: MainAxisSize.min, children: [
                Container(
                    decoration: Global.getBg(MyColor.Green, 20),
                    height: 24,
                    width: 24,
                    margin: EdgeInsets.only(right: 6),
                    child: LocalImage(icon, padding: EdgeInsets.all(4))),
                Text("$title", style: TextStyle(fontSize: 15, color: MyColor.Green))
              ])),
          Row(mainAxisAlignment: MainAxisAlignment.end, children: [
            hideSee
                ? Container()
                : GestureDetector(
                    onTap: onSeeTap,
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                        padding: EdgeInsets.all(8),
                        child: Row(mainAxisSize: MainAxisSize.min, children: [
                          LocalImage("eye.png", height: 16, width: 20),
                          Text("查看", style: TextStyle(fontSize: 13, color: MyColor.Green))
                        ]))),
            hideDownload
                ? Container()
                : GestureDetector(
                    onTap: onDownloadTap,
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                        padding: EdgeInsets.all(8),
                        child: Row(mainAxisSize: MainAxisSize.min, children: [
                          LocalImage("direct-download.png", height: 16, width: 20),
                          Text("下載", style: TextStyle(fontSize: 13, color: MyColor.Green))
                        ])))
          ])
        ]));
  }
}

///單字 & 片語
class WordWidget extends StatefulWidget {
  dynamic data;

  WordWidget(this.data);

  @override
  State<StatefulWidget> createState() {
    return _WordWidget();
  }
}

class _WordWidget extends State<WordWidget> {
  List<dynamic> words = [];

  @override
  void initState() {
    words = widget.data["vocabularies"];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: Global.getWhiteBg_shadow(8, MyColor.DD),
        padding: EdgeInsets.all(12),
        margin: EdgeInsets.fromLTRB(12, 0, 12, 12),
        child: Column(children: [
          Row(mainAxisAlignment: MainAxisAlignment.center, children: [
            LocalImage("words.png", height: 24, width: 32),
            Text("單字 & 片語", style: TextStyle(fontSize: 14, color: MyColor.Orange, fontWeight: FontWeight.bold))
          ]),
          Container(height: 0.5, color: MyColor.Orange, margin: EdgeInsets.only(top: 6, bottom: 16)),
          ListView.builder(
              itemCount: words.length,
              shrinkWrap: true,
              padding: EdgeInsets.only(bottom: 16),
              physics: NeverScrollableScrollPhysics(),
              itemBuilder: (BuildContext context, int index) {
                return ItemWord(index + 1, words[index]);
              }),
          Button("練習", bgColor: MyColor.Orange, radius: 4, width: double.infinity, height: 32, fontSize: 12, onTap: () {
            showBottomDialog(context, DialogTest(widget.data["classroomId"]));
          }),
        ]));
  }
}

class ItemWord extends StatefulWidget {
  int number;
  dynamic word;

  ItemWord(this.number, this.word);

  @override
  State<StatefulWidget> createState() {
    return _ItemWord();
  }
}

class _ItemWord extends State<ItemWord> {
  starTap() {
    HttpGo(context).post("/HiNote/SetFavoriteVocabulary",
        {"studentId": Global.studentId, "vocabularyId": widget.word["vocabularyId"], "isFavorite": !widget.word["isFavorite"]}, (data) {
      widget.word["isFavorite"] = !widget.word["isFavorite"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  // "isFavorite": false,
  // "isHide": false
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.fromLTRB(16, 5, 0, 5),
      child: Row(children: [
        Expanded(child: Text("${widget.number}.${widget.word["word"]}", style: TextStyle(fontSize: 12, color: MyColor.C7D))),
        Expanded(child: Text("${widget.word["meaning"]}", style: TextStyle(fontSize: 12, color: MyColor.C7D))),
        LocalImage(widget.word["isFavorite"] ? "star_g.png" : "star.png", width: 18, padding: EdgeInsets.all(3), onTap: starTap)
      ]),
    );
  }
}

class DialogTest extends StatelessWidget {
  int classroomId;

  DialogTest(this.classroomId);

  @override
  Widget build(BuildContext context) {
    startWordTest() {
      HttpGo(context).post("/HiNote/GetVocabularyQuiz", {"classroomId": classroomId, "vocabularyQuizType": 1}, (data) {
        PageUtil().openReplace(context, WordsTest(data));
      }, (code, error) => showToast(error));
    }

    startShowCard() {
      HttpGo(context).post("/HiNote/GetVocabularyQuiz", {"classroomId": classroomId, "vocabularyQuizType": 2}, (data) {
        PageUtil().openReplace(context, WordsShowCard(data));
      }, (code, error) => showToast(error));
    }

    return Container(
        width: double.infinity,
        padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
        decoration: BoxDecoration(color: Color(0xfffffffff), borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        child: Container(
            padding: EdgeInsets.all(8),
            decoration: BoxDecoration(color: Color(0xfffee4cb), borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
            child: Column(mainAxisSize: MainAxisSize.min, children: [
              Container(
                  alignment: Alignment.centerRight,
                  child: LocalImage("cross.png", width: 24, padding: EdgeInsets.all(8), onTap: () {
                    PageUtil().back(context);
                  })),
              Button("字彙測驗", fontColor: MyColor.Orange, bgColor: Color(0xfffff5ef), radius: 4, onTap: startWordTest),
              Container(height: 16),
              Button("閃示卡", fontColor: MyColor.Orange, bgColor: Color(0xfffff5ef), radius: 4, onTap: startShowCard),
              Container(height: 24)
            ])));
  }
}

///教師註記  yes
class TeacherNote extends StatelessWidget {
  dynamic data;
  List<dynamic> teacherCommnets = [];
  String evUrl = "";

  TeacherNote(this.data) {
    teacherCommnets = data["teacherCommnets"];
    evUrl = data["evUrl"] ?? "";
  }

  @override
  Widget build(BuildContext context) {
    String comment = "";
    for (var item in teacherCommnets) {
      comment = comment + "${item["type"]}\n${item["content"]}";
    }
    return Container(
        decoration: Global.getWhiteBg_shadow(8, MyColor.DD),
        padding: EdgeInsets.all(12),
        margin: EdgeInsets.fromLTRB(12, 0, 12, 12),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Row(mainAxisAlignment: MainAxisAlignment.center, children: [
            LocalImage("teacher_o.png", height: 24, width: 32),
            Text("教師註記", style: TextStyle(fontSize: 14, color: MyColor.Orange, fontWeight: FontWeight.bold))
          ]),
          Container(height: 0.5, color: MyColor.Orange, margin: EdgeInsets.only(top: 6, bottom: 16)),
          Text(comment, style: TextStyle(fontSize: 12, height: 2, color: MyColor.C7D)),
          Container(height: 16),
          Visibility(
              visible: evUrl.isNotEmpty,
              child: Button("查看EV", bgColor: MyColor.Orange, radius: 4, width: double.infinity, height: 32, fontSize: 12, onTap: () {
                PageUtil().open(context, WebPage("查看EV", evUrl, showBrowser: true));
              })),
        ]));
  }
}

///我的筆記 yes
class MyNote extends StatefulWidget {
  dynamic data;

  MyNote(this.data);

  @override
  State<StatefulWidget> createState() {
    return _MyNote();
  }
}

class _MyNote extends State<MyNote> {
  dynamic note;
  TextEditingController controller = TextEditingController();
  bool editMode = false;

  click() {
    if (editMode) {
      editNote();
    } else {
      controller.text = note["content"] ?? "";
      editMode = !editMode;
      setState(() {});
    }
  }

  editNote() {
    Map<String, dynamic> params = {
      "classroomId": widget.data["classroomId"],
      "noteContent": controller.text,
    };
    if (note != null && note["noteId"] != null) {
      params["noteId"] = note["noteId"];
    }
    HttpGo(context).post("/HiNote/UpdateReviewNote", params, (data) {
      note["content"] = controller.text;
      editMode = !editMode;
      setState(() {});
    }, (code, error) => showToast(error));
  }

  @override
  void initState() {
    note = widget.data["note"] ?? {};
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    print(note);
    return Container(
        decoration: Global.getWhiteBg_shadow(8, MyColor.DD),
        padding: EdgeInsets.all(12),
        margin: EdgeInsets.fromLTRB(12, 0, 12, 12),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Row(mainAxisAlignment: MainAxisAlignment.center, children: [
            LocalImage("notes.png", height: 24, width: 32),
            Text("我的筆記", style: TextStyle(fontSize: 14, color: MyColor.Orange, fontWeight: FontWeight.bold))
          ]),
          Container(height: 0.5, color: MyColor.Orange, margin: EdgeInsets.only(top: 6, bottom: 16)),
          editMode
              ? Container(child: NormalInput(controller: controller, maxLines: 0))
              : Text(note["content"] ?? "", style: TextStyle(fontSize: 12, height: 2, color: MyColor.C7D)),
          Container(height: 16),
          Button(editMode ? "完成" : "編輯",
              bgColor: MyColor.Orange, radius: 4, width: double.infinity, height: 32, fontSize: 12, onTap: click),
        ]));
  }
}

///課後作業
class Homework extends StatefulWidget {
  String teacherName;
  String teacherId;
  dynamic homework;
  Function() refreshData;

  Homework(this.teacherName, this.teacherId, this.homework, this.refreshData);

  @override
  State<StatefulWidget> createState() {
    return _HomeWork();
  }
}

class _HomeWork extends State<Homework> {
  bool isSubmitWork = false;
  bool isFeedBack = false;
  List<dynamic> files = [];
  String audioUrl = "";

  @override
  Widget build(BuildContext context) {
    String questionTime = "";
    String answerTime = "";
    String feedBackTime = "";
    if (widget.homework["questionDate"] != null) questionTime = getStrTime(getTimeByUtc(widget.homework["questionDate"]), DateUtil.YMDHM);
    if (widget.homework["answerDate"] != null) answerTime = getStrTime(getTimeByUtc(widget.homework["answerDate"]), DateUtil.YMDHM);
    if (widget.homework["teacherFeedBackTime"] != null)
      feedBackTime = getStrTime(getTimeByUtc(widget.homework["teacherFeedBackTime"]), DateUtil.YMDHM);

    isSubmitWork = widget.homework["answer"] != null || widget.homework["files"] != null;
    isFeedBack = isSubmitWork && widget.homework["teacherFeedBack"] != null;
    if (widget.homework["files"] != null) {
      files = widget.homework["files"]["files"] ?? [];
      List<dynamic> record = widget.homework["files"]["record"] ?? [];
      if (record.length > 0) {
        audioUrl = record[0]["url"];
      }
    }

    return Container(
        margin: EdgeInsets.fromLTRB(12, 0, 12, 12),
        padding: EdgeInsets.all(12),
        decoration: Global.getWhiteBg_shadow(8, MyColor.DD),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Row(mainAxisAlignment: MainAxisAlignment.center, children: [
            LocalImage("studying.png", height: 24, width: 32),
            Text("課後作業", style: TextStyle(fontSize: 14, color: MyColor.Orange, fontWeight: FontWeight.bold))
          ]),
          Container(height: 0.5, color: MyColor.Orange, margin: EdgeInsets.only(top: 6, bottom: 8)),
          TeacherTime("${widget.teacherName}", "$questionTime"),
          Text("Question：${widget.homework["question"]}", style: TextStyle(fontSize: 12, height: 2, color: MyColor.C7D)),
          Container(height: 32),
          isSubmitWork
              ? Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                  StudentTime("$answerTime"),
                  Container(
                      decoration: Global.getBg(Color(0xffecf9f9), 8),
                      padding: EdgeInsets.all(12),
                      margin: EdgeInsets.fromLTRB(0, 8, 0, 24),
                      width: double.infinity,
                      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                        Container(
                            alignment: Alignment.centerRight,
                            child: LocalImage("edit.png", width: 24, padding: EdgeInsets.all(4), onTap: () {
                              PageUtil().open(
                                  context,
                                  SubmitHomeWork(widget.teacherName, widget.teacherId, questionTime, widget.homework["questionId"],
                                      widget.homework["question"],
                                      onSendDone: widget.refreshData));
                            })),
                        Text("Answer：${widget.homework["answer"]}",
                            style: TextStyle(fontSize: 12, color: MyColor.Green, fontWeight: FontWeight.bold)),
                        Container(height: 8),
                        // Visibility(
                        //     visible: filePath.isNotEmpty,
                        //     child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
                        //       LocalImage("file_g.png", width: 24, padding: EdgeInsets.fromLTRB(8, 0, 8, 0)),
                        //       Expanded(child: Text("$filePath", style: TextStyle(fontSize: 12, color: MyColor.Green)))
                        //     ])),
                        ListView.builder(
                            shrinkWrap: true,
                            physics: NeverScrollableScrollPhysics(),
                            itemCount: files.length,
                            itemBuilder: (c, i) {
                              return Container(
                                  padding: EdgeInsets.only(bottom: 6),
                                  child: Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
                                    LocalImage("file_g.png", width: 24, padding: EdgeInsets.fromLTRB(8, 0, 8, 0)),
                                    Expanded(child: Text("${files[i]["fileName"]}", style: TextStyle(fontSize: 12, color: MyColor.Green)))
                                  ]));
                            }),
                        Visibility(visible: audioUrl.isNotEmpty, child: AudioPlayBarNet(audioUrl))
                      ])),
                  Visibility(visible: isFeedBack, child: TeacherTime("${widget.teacherName}", "$feedBackTime")),
                  Visibility(
                    visible: isFeedBack,
                    child: Text("${widget.homework["teacherFeedBack"]}", style: TextStyle(fontSize: 12, height: 2, color: MyColor.C7D)),
                  ),
                ])
              : Button("繳交作業", bgColor: MyColor.Orange, radius: 4, width: double.infinity, height: 32, fontSize: 12, onTap: () {
                  PageUtil().open(
                      context,
                      SubmitHomeWork(
                          widget.teacherName, widget.teacherId, questionTime, widget.homework["questionId"], widget.homework["question"],
                          onSendDone: widget.refreshData));
                })
        ]));
  }
}

class TeacherTime extends StatelessWidget {
  String teacher;
  String time;

  TeacherTime(this.teacher, this.time);

  @override
  Widget build(BuildContext context) {
    return Row(children: [
      LocalImage("teacher_b.png", width: 24, padding: EdgeInsets.all(4)),
      Expanded(child: Text(teacher, style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: Color(0xff005eab)))),
      Text(time, style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold, color: MyColor.C5))
    ]);
  }
}

class StudentTime extends StatelessWidget {
  String time;

  StudentTime(this.time);

  @override
  Widget build(BuildContext context) {
    return Row(children: [
      LocalImage("student.png", width: 24, padding: EdgeInsets.all(4)),
      Expanded(child: Text("${Global.userName}", style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: MyColor.Green))),
      Text(time, style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold, color: MyColor.C5))
    ]);
  }
}
